package com.bxl.netty.rpc.register.server;

import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.MsgResponseContent;
import com.bxl.netty.rpc.common.message.PackageMsg;
import com.bxl.netty.rpc.common.message.RegisterContent;
import com.bxl.netty.rpc.common.message.RpcHeader;
import com.bxl.netty.rpc.register.server.service.RegisterOperDefine;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class RegisterServerHandler extends SimpleChannelInboundHandler<PackageMsg<RegisterContent>> {
    private RegisterServerContext context;

    public RegisterServerHandler() {

    }

    public RegisterServerHandler(Context context) {
        assert context == null;
        this.context = (RegisterServerContext)context;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PackageMsg<RegisterContent> msg) throws Exception {
        int flag = 0;//成功
        MsgResponseContent deal = null;
        try {
            RegisterOperDefine registerOperDefine = RegisterOperDefine.getRegisterOperDefine(msg.getHeader().getFlag());
            deal = registerOperDefine.deal(msg, context);
        } catch (Exception e) {
            flag = 1;
            e.printStackTrace();//失败
        }
        RpcHeader header = new RpcHeader();
        header.setFlag(flag);
        header.setRequestID(msg.getHeader().getRequestID());
        PackageMsg<MsgResponseContent> rtnMsg = new PackageMsg<MsgResponseContent>();
        rtnMsg.setHeader(header);
        rtnMsg.setContent(deal);
        ctx.writeAndFlush(rtnMsg);

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception{
        System.out.println(ctx.channel().remoteAddress());
        ctx.disconnect();
    }

}
